package com.dragon.aipictures.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.dragon.aipictures.Exception.BusinessException;
import com.dragon.aipictures.Exception.StateCode;
import com.dragon.aipictures.util.ThrowUtil;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import static com.dragon.aipictures.constant.UrlConstant.ALLOW_CONTENT_TYPES;

@Component
public class UrlPictureUpload extends PictureUploadTemplate {
    @Override
    public String validPicture(Object inputSource) {
        //校验URl的合法性，怎么校验？
        //校验非空第一步
        String fileUrl = (String) inputSource;
        ThrowUtil.throwIf(ObjectUtil.isEmpty(fileUrl), StateCode.PARAMS_ERROR, "文件地址为空");

//        String suffix = FileUtil.getSuffix(fileUrl);
//        ThrowUtil.throwIf(!ALLOW_CONTENT_TYPES.contains(suffix),StateCode.PARAMS_ERROR,"仅支持jpeg, jpg, png, webp,bmp,gif格式");

        //校验URL格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(StateCode.PARAMS_ERROR, "文件地址格式不对");
        }

        //校验协议
        ThrowUtil.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"), StateCode.PARAMS_ERROR, "仅支持HTTP或HTTPS协议的文件地址");

        //发送HEAD请求验证文件是否存在
        HttpResponse httpResponse = null;
        try {
            httpResponse=HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
                throw new BusinessException(StateCode.PARAMS_ERROR,"文件源不存在");
            }
            String contentType = httpResponse.header("Content-Type");
            String suffix="jpg";
            if (StrUtil.isNotBlank(contentType)) {
                suffix=contentType.replace("image/","");
                System.out.println(contentType);
                ThrowUtil.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),StateCode.PARAMS_ERROR,"不支持该格式的图片");
            }
            String contentLengthStr = httpResponse.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                long contentLength = Long.parseLong(contentLengthStr);
                ThrowUtil.throwIf(contentLength>2*ONE_M,StateCode.PARAMS_ERROR,"文件大小不能超过 2MB");
                }catch (NumberFormatException e){
                    throw new BusinessException(StateCode.PARAMS_ERROR,"文件大小格式异常");
                }
            }
            return suffix;
        } finally {
            if (httpResponse!=null) {
                httpResponse.close();
            }
        }
    }

    @Override
    public String getOriginalFileName(Object inputSource) {
        String fileUrl=(String)inputSource;
        return FileUtil.mainName(fileUrl);
    }

    @Override
    public void processFile(Object inputSource, File file) {
        String fileUrl=(String)inputSource;
        HttpUtil.downloadFile(fileUrl,file);
    }
}
